import { onMounted, ref} from "vue"
import type { postItem, configType, userInfo } from "@/types/userInfo.d.ts"
import { getPosts as getPostsApi , getConfig as getConfigApi, like as likeApi, login as loginApi} from "@/api/user"
import useAppStore from "@/stores/modules/app"


export const useScript = function(){
  const appStore = useAppStore()
  const isloding = ref(false)
  const loadEnd = ref(false)
  const userInfo = ref<userInfo>()
  const config = ref<configType>()
  const posts = ref<postItem[]>([])
  const params = ref({
    page: 1,
    limit: 2,
    total: 0
  })
  async function getUserInfo()
  {
    // 获取url后面参数 userid
    const url = window.location.href
    const userid = url.split('?')[1].split('=')[1]
    if(!userid) {
      console.log('未获取到userid')
      return
    }
    const res = await loginApi({userid})
    if(res.code)
    {
      userInfo.value = res.data
      appStore.setToken(res.data.token);
      Promise.all([getConfig(),getPosts()])
    }else{
      console.log('登录失败')
    }
  }

  async function getPosts(){
    if(isloding.value || loadEnd.value) return;
    isloding.value = true
    const res = await getPostsApi({page: params.value.page, limit: params.value.limit})
    console.log(res)
    if(res.code)
    {
      params.value.total = res.data.total
      params.value.page = res.data.page * 1 + 1
      posts.value.push(...res.data.list)
      loadEnd.value = res.data.list.length < params.value.limit
      isloding.value = false 
    }
  }
  

  async function getConfig()
  {
    const res = await getConfigApi()
    if(res.code)
    {
      config.value = res.data
    }
  }


  async function handleScroll(event:any){
    const { scrollTop, clientHeight, scrollHeight } = event.target;

    // 判断滚动到底部
    if (scrollTop + clientHeight >= scrollHeight - 10 && isloding) {
      await getPosts()
    }
  }
  async function handlePost (id: number) {
    // handle the post event here
    const res = await likeApi(id)
    if(res.code)
    {
      const post = posts.value.find((item)=>item.id === id)
      if(post)
      {
        post.is_like = res.data.is_like
        console.log(res.data.is_like)
        post.voteNum += res.data.is_like ? 1 : -1
      }
    }
  }
  

  onMounted(async()=>{
    await getUserInfo()
  })



  return {
    posts,
    isloding,
    loadEnd,
    config,
    userInfo,
    handleScroll,
    handlePost
  }
}